<template>
  <div>
    <el-card style="margin: 20px 0px">
      <CategorySelect
        @getCategoryId="getCategoryId"
        :isShow="!isShowTable"
      ></CategorySelect>
    </el-card>
    <el-card>
      <div v-show="isShowTable">
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!category3Id"
          @click="addAttr"
          >添加属性</el-button
        >
        <!-- 表格：展示平台属性 -->
        <el-table style="width: 100%" border :data="attrList">
          <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column>
          <el-table-column prop="attrName" label="属性名称" width="150">
          </el-table-column>
          <el-table-column prop="prop" label="属性值列表" width="width">
            <template slot-scope="{ row, $index }">
              <el-tag
                type="success"
                v-for="attrValue in row.attrValueList"
                :key="attrValue.id"
                style="margin: 20px 0"
              >
                {{ attrValue.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="属性值列表" width="150">
            <template slot-scope="{ row, $index }">
              <el-button
                type="warning"
                icon="el-icon-edit"
                size="mini"
                @click="updataAttr(row)"
              >
              </el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="DeleteAttr(row)"
              >
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 添加修改属性的表单 -->
      <div v-show="!isShowTable">
        <el-form :inline="true" ref="form" label-width="80px" :model="attrInfo">
          <el-form-item label="属性名">
            <el-input
              placeholder="请输入属性名"
              v-model="attrInfo.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addAttrValue()"
          :disabled="!attrInfo.attrName"
          >添加属性值</el-button
        >
        <el-button @click="isShowTable = true">取消</el-button>
        <el-table
          style="width: 100%; margin: 20px 0"
          border
          :data="attrInfo.attrValueList"
        >
          <el-table-column align="center" type="index" label="序号" width="80">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称" width="width">
            <template slot-scope="{ row, $index }">
              <!-- 这里要显示模式与编辑模块切换 -->
              <el-input
                v-model="row.valueName"
                size="mini"
                v-if="row.flag"
                @blur="toLook(row)"
                @keyup.native.enter="toLook(row)"
                placeholder="请输入属性值名称"
                :ref="$index"
              ></el-input>
              <span v-else style="display: block" @click="toEdit(row, $index)">
                {{ row.valueName }}
              </span>
            </template></el-table-column
          >
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <!-- 这里要注意，这个模板的elementUI版本低，所以要用onConfirm而不是官网上的confirm -->
              <el-popconfirm
                :title="`确定删除${row.valueName}吗？`"
                @onConfirm="deleteAttrValue($index)"
              >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  slot="reference"
                ></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <el-button
          type="primary"
          @click="AddOrUpdataAttr"
          :disabled="attrInfo.attrValueList.length < 1 || isEmpty || isRepat"
          >保存</el-button
        >
        <el-button @click="isShowTable = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
//按需引入，使用里面的深拷贝
import cloneDeep from "lodash/cloneDeep";
export default {
  name: "Attr",
  data() {
    return {
      category1Id: "",
      category2Id: "",
      category3Id: "",
      attrList: [],
      //控制添加修改属性表格的显示与隐藏
      isShowTable: true,
      //收集新增属性或者修改属性的数据
      attrInfo: {
        attrName: "string", //属性名
        attrValueList: [
          //属性值，属性值可以有多个
          {
            attrId: 0, //对应属性名的id
            id: 0,
            valueName: "string",
          },
        ],
        categoryId: 0, //三级分类的id
        categoryLevel: 0, //服务器也要区分几级id
        id: 0,
      },
      isEmpty: false, //当前聚集的input是否为空
      isRepat: false, //当前聚集的input是否重复
    };
  },
  methods: {
    //自定义事件的回调，把对应的数据展示出来
    getCategoryId({ category1Id, category2Id, category3Id }) {
      if (category1Id && category2Id && category3Id) {
        //发请求展示数据
        this.category1Id = category1Id;
        this.category2Id = category2Id;
        this.category3Id = category3Id;
        this.getAttrList();
      }
    },
    //发请求展示详情数据
    async getAttrList() {
      const { category1Id, category2Id, category3Id } = this;
      let result = await this.$API.attr.reqAttrList(
        category1Id,
        category2Id,
        category3Id
      );
      if (result.code == 200) {
        this.attrList = result.data;
      }
    },
    //添加属性值
    addAttrValue(row) {
      //只有当前聚集的input不为空且不能重复时才能添加属性值,或者当前没有属性值
      if (
        (!this.isEmpty && !this.isRepat) ||
        this.attrInfo.attrValueList.length == 0
      ) {
        //向属性值的数组中添加元素
        //attrId:相应属性的id，valueName:
        this.attrInfo.attrValueList.push({
          attrId: this.attrInfo.id,
          valueName: "",
          flag: true, //给每一个属性值加一个flag，分别控制每一个的切换
        });

        //点击添加属性值的时候，本来的input要失去焦点，然后新建的要获得焦点
        this.$nextTick(() => {
          this.$refs[this.attrInfo.attrValueList.length - 1].focus();
        });
      } else {
        //若添加不成功，则还让聚集在当前input
        if (this.attrInfo.attrValueList.length - 1 > 0) {
          this.$refs[this.attrInfo.attrValueList.length - 1].focus();
        }
      }
    },
    //添加属性
    addAttr() {
      this.isShowTable = false;
      //清除数据
      //收集三级分类的id
      this.attrInfo = {
        attrName: "", //属性名
        attrValueList: [
          //属性值
        ],
        categoryId: this.category3Id, //三级分类id
        categoryLevel: 3,
      };
    },
    //修改某个属性
    updataAttr(row) {
      this.isShowTable = false;

      //把当前选中的属性给attrInfo，因为数据复杂，所以用深拷贝
      this.attrInfo = cloneDeep(row);
      //在修改的时候给对应的属性加个flag，但要是响应式的，因为本来从服务器返回的里面没有flag
      this.attrInfo.attrValueList.forEach((item) => {
        this.$set(item, "flag", false); //默认false
      });
    },
    //失去焦点时，切换为查看模式，展示span
    toLook(row) {
      //要判断用户输入的不能为空
      if (row.valueName.trim() == "") {
        this.$message("输入不能为空");
        this.isEmpty = true;
        return;
      }
      //当输入不为空时才会正常进行
      this.isEmpty = false;

      //判断不能输入的是已有的属性值
      this.isRepat = this.attrInfo.attrValueList.some((item) => {
        if (row != item) {
          return row.valueName == item.valueName;
        }
      });
      if (this.isRepat) {
        this.$message("属性值重复");
        return;
      }
      row.flag = false;
    },
    //在span的时候，点击之后会进入编辑模块
    toEdit(row, index) {
      row.flag = true;
      //让进入编辑模块的时候，就要自动聚集
      this.$nextTick(() => {
        this.$refs[index].focus(); //这里不能用.来获取，因为index是一个变量
      });
    },
    //删除属性
    deleteAttrValue(index) {
      //删除属性值
      this.attrInfo.attrValueList.splice(index, 1);
    },
    //点击保存后，再向服务器发没请求并更新数据
    async AddOrUpdataAttr() {
      //整理参数，发给服务器的数据，不能有空，也不能出现flag字段
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter(
        (item) => {
          //过滤掉属性值是空的
          if (item.valueName != "") {
            //删除flag属性
            delete item.flag;
            return true;
          }
        }
      );
      try {
        //准备好给服务器的数据后，发请求
        await this.$API.attr.reqAddOrChangeAttr(this.attrInfo);
        //切换为展示平台属性
        this.isShowTable = true;
        //提示成功
        this.$message({ type: "success", message: "保存成功" });
        //但发请求更新数据
        this.getAttrList();
      } catch (error) {
        console.log(error.message);
      }
    },
    //删除属性
    async DeleteAttr(row) {
      //发送请求删除
      try {
        await this.$API.attr.reqDeleteAttr(row.id);
        this.getAttrList();
        this.$message({ type: "success", message: "删除成功" });
      } catch (error) {
        console.log(error.message);
      }
    },
  },
};
</script>

<style>
</style>